package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.PageInfo;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/3/2 20:05
 * @version: 0.0.1
 * @modified By:
 */
@Service
public class UsersService {
    @Autowired
    private UserInfoService userInfoService;
    
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private RecommendUserService recommendUserService;


    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private BlackListService blackListService;

    /**
     * @description 查询用户信息
     * @author
     * @date
     * @param
     *@return
     */
    public UserInfoVo queryUserInfo(Long userId, Long huanxinID) {
        User user= UserThreadLocal.get();
        Long userId2=user.getId();
        if(null!=userId){
            userId2=userId;
        }else if(null!=huanxinID){
            userId2=huanxinID;
        }
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId2);
        if(null==userInfo){
            return null;
        }
        UserInfoVo userInfoVo=new UserInfoVo();
        userInfoVo.setAge(userInfo.getAge()==null?null:userInfo.getAge().toString());
        userInfoVo.setAvatar(userInfo.getLogo());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setEducation(userInfo.getEdu());
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setId(userInfo.getUserId());
        userInfoVo.setIncome(userInfo.getIncome()+"K");
        userInfoVo.setMarriage(userInfo.getMarriage()=="已婚"?1:0);
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setProfession(userInfo.getIndustry());
        return userInfoVo;
    }

    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user=UserThreadLocal.get();
        UserInfo userInfo=new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(),"man")? SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(),"K",""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage()==1?"已婚":"未婚");
        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    public CountsVo queryCounts() {
        User user=UserThreadLocal.get();
        Long eachLoveCount = this.userLikeApi.queryEachLikeCount(user.getId());
        Long loveCount = this.userLikeApi.queryLikeCount(user.getId());
        Long fanCount = this.userLikeApi.queryFanCount(user.getId());
        CountsVo countsVo=new CountsVo();
        countsVo.setEachLoveCount(eachLoveCount);
        countsVo.setLoveCount(loveCount);
        countsVo.setFanCount(fanCount);
        return countsVo;
    }

    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickName) {
        User user=UserThreadLocal.get();
        PageResult pageResult=new PageResult();
        pageResult.setCounts(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<Long>likeUserIds=new ArrayList<>();
        switch (type){
            case 1:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryEachLikeList(user.getId(), page, pageSize);
                List<UserLike> records = pageInfo.getRecords();
                for (UserLike record : records) {
                    if(!likeUserIds.contains(record.getUserId())){
                        likeUserIds.add(record.getUserId());
                    }
                }
                break;
            }
            case 2:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(user.getId(), page, pageSize);
                List<UserLike> records = pageInfo.getRecords();
                for (UserLike record : records) {
                    if(!likeUserIds.contains(record.getUserId())){
                        likeUserIds.add(record.getLikeUserId());
                    }
                }
                break;
            }
            case 3:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(user.getId(), page, pageSize);
                List<UserLike> records = pageInfo.getRecords();
                for (UserLike record : records) {
                    if(!likeUserIds.contains(record.getUserId())){
                        likeUserIds.add(record.getUserId());
                    }
                }
                break;
            }
            case 4:{
                PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(user.getId(), page, pageSize);
                List<Visitors> records = pageInfo.getRecords();
                for (Visitors record : records) {
                    if(!likeUserIds.contains(record.getUserId())){
                        likeUserIds.add(record.getVisitorUserId());
                    }
                }
                break;
            }
            default:{
                pageResult.setItems(null);
                break;
            }
        }
        if(CollectionUtils.isEmpty(likeUserIds)){
            return pageResult;
        }
        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.in("user_id",likeUserIds);
        if(StringUtils.isNotEmpty(nickName)){
            queryWrapper.like("nick_name",nickName);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<LikeUserVo>likeUserVoList=new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            LikeUserVo likeUserVo=new LikeUserVo();
            likeUserVo.setId(userInfo.getUserId());
            Double score=this.recommendUserService.queryScore(user.getId(),userInfo.getUserId());
            if(score==0){
                score= RandomUtils.nextDouble(30,90); //特殊情况下的缘分值的生成，一般情况下都会有值
            }
            likeUserVo.setMatchRate(score.intValue());
            likeUserVo.setNickname(userInfo.getNickName());
            likeUserVo.setMarriage(StringUtils.equalsIgnoreCase(userInfo.getMarriage(),"已婚")?1:0);
            likeUserVo.setGender(userInfo.getSex().name().toLowerCase());
            likeUserVo.setCity(userInfo.getCity());
            likeUserVo.setEducation(userInfo.getEdu());
            likeUserVo.setAvatar(userInfo.getLogo());
            likeUserVo.setAge(userInfo.getAge());
            likeUserVoList.add(likeUserVo);
        }
        pageResult.setItems(likeUserVoList);
        return pageResult;
    }

    public Boolean disLikeUser(Long userId) {
        User user=UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), userId);
    }

    public Boolean saveLikeFan(Long userId) {
        User user=UserThreadLocal.get();
        String s = this.userLikeApi.saveUserLike(user.getId(), userId);
        if(StringUtils.isEmpty(s)){
            return false;
        }
        return true;
    }

    public SettingsVo querySettings() {
        User user=UserThreadLocal.get();
        SettingsVo settingsVo=new SettingsVo();
        settingsVo.setPhone(user.getMobile());
        settingsVo.setId(user.getId());
        //查询通用设置
        Settings settings= this.settingsService.querySettingsByUserId(user.getId());
        if(null!=settings){
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }
        //查询陌生人的问题
        Question question = this.questionService.queryQuestion(user.getId());
        if(null!=question){
            settingsVo.setStrangerQuestion(question.getTxt());
        }

        return settingsVo;
    }

    public Boolean saveStrangerQuestion(String content) {
        User user=UserThreadLocal.get();
        return this.questionService.saveQuestion(user.getId(),content);
    }

    public PageResult queryBlackList(Integer page, Integer pageSize) {
        User user=UserThreadLocal.get();
        IPage<BlackList> blackListIPage = this.blackListService.queryList(user.getId(), page, pageSize);
        PageResult pageResult=new PageResult();
        pageResult.setCounts(new Long(blackListIPage.getTotal()).intValue());
        pageResult.setPages(new Long(blackListIPage.getPages()).intValue());
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<BlackList> records = blackListIPage.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return pageResult;
        }
        List<Long>userIds=new ArrayList<>();
        for (BlackList record : records) {
            if(!userIds.contains(record.getBlackUserId())){
                userIds.add(record.getBlackUserId());
            }
        }
        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<BlackUserVo>blackUserVos=new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            BlackUserVo blackUserVo=new BlackUserVo();
            blackUserVo.setAge(userInfo.getAge());
            blackUserVo.setAvatar(userInfo.getLogo());
            blackUserVo.setGender(userInfo.getSex().name().toLowerCase());
            blackUserVo.setId(userInfo.getUserId());
            blackUserVo.setNickname(userInfo.getNickName());
            blackUserVos.add(blackUserVo);
        }
        pageResult.setItems(blackUserVos);
        return pageResult;
    }

    public Boolean deleteBlackList(Long userId) {
        User user=UserThreadLocal.get();
        Boolean bool=this.blackListService.deleteBlackById(user.getId(),userId);
        return bool;
    }
}
